package beans;


import database.DatabaseConnection;

import java.io.PrintWriter;

import java.math.BigDecimal;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;

import obj.Teachers;

import oracle.adf.share.logging.ADFLogger;
import oracle.adf.view.rich.component.rich.data.RichTree;

import org.apache.myfaces.trinidad.model.ChildPropertyTreeModel;
import org.apache.myfaces.trinidad.model.ModelUtils;
import org.apache.myfaces.trinidad.model.RowKeySet;
import org.apache.myfaces.trinidad.model.RowKeySetTreeImpl;
import org.apache.myfaces.trinidad.model.TreeModel;


public class InfoTeachers {
    TreeModel model;
    private Teachers root;
    List<SelectItem> listaProfi = new ArrayList<SelectItem>();

    private RichTree richTree;
    private RowKeySet disclosedRowKeys = new RowKeySetTreeImpl();
    //pt search
    private String searchString = "";
    private String searchType = "CONTAIN";
    private List searchAttributes = new ArrayList();
    ADFLogger logger = ADFLogger.createADFLogger(this.getClass());  
    public InfoTeachers() {
        super();
        orar();
        tree1();
    }

    public void orar() {
        String sql = "SELECT nume,id_prof from profesori ORDER BY profesori.nume";
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PrintWriter pw = null;
        try {
            con = DatabaseConnection.getConectare();
            System.out.println(con);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                BigDecimal id_prof = rs.getBigDecimal("id_prof");
                String nume = rs.getString("nume");
                Teachers profObj = new Teachers(id_prof, nume);
                listaProfi.add(new SelectItem(id_prof, nume));
            }

        } catch (ClassNotFoundException ex) {

        } catch (SQLException ex) {
            System.out.println("err sql" + ex);

        }

        finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {

            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }

        }
    }

    public List<SelectItem> getListaProfi() {
        return listaProfi;
    }

    public void tree() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PrintWriter pw = null;
        try {
            con = DatabaseConnection.getConectare();
            stmt = con.createStatement();
            rs =
 stmt.executeQuery(" select nume, id_prof, supervisor_id, level " + " from profesori " + " connect by prior id_prof = supervisor_id start with id_prof=1");
            Map<BigDecimal, Teachers> elem = new HashMap<BigDecimal, Teachers>();
            rs.next();
            BigDecimal nr = rs.getBigDecimal("id_prof");
            Teachers p = new Teachers(nr, rs.getString("nume")); //radacina
            System.out.println("nr" + nr);
            elem.put(nr, p);
            String string = elem.toString();
            System.out.println("elem" + string);
            while (rs.next()) {
                BigDecimal FIU = rs.getBigDecimal("id_prof");
                BigDecimal TATA = rs.getBigDecimal("supervisor_id");
                System.out.println("n=" + FIU);
                Teachers s = new Teachers(FIU, rs.getString("nume"));
                if (elem.containsKey(TATA)) {

                    if (elem.get(TATA) != null) {
                        Teachers profesori = (Teachers)elem.get(TATA);
                        System.out.println("X" + profesori.getProf_id());
                        profesori.getChildren().add(s);
                    }

                }
                elem.put(FIU, s);
            }
            model = new ChildPropertyTreeModel(p, "children");
            System.out.println(p);
        } catch (ClassNotFoundException ex) {

        } catch (SQLException ex) {

        }

        finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {

            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }
        }
    }

    public void tree1() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PrintWriter pw = null;
        try {
            con = DatabaseConnection.getConectare();
            stmt = con.createStatement();
            rs =
 stmt.executeQuery(" select nume, id_prof, supervisor_id, level " + " from profesori " + " connect by prior id_prof = supervisor_id START WITH supervisor_id     is null");
            Map<BigDecimal, Teachers> elem = new HashMap<BigDecimal, Teachers>();
            Teachers p = new Teachers(BigDecimal.ZERO, "PROFESORI");
            while (rs.next()) {
                BigDecimal FIU = rs.getBigDecimal("id_prof");
                BigDecimal TATA = rs.getBigDecimal("supervisor_id");
                Teachers s = new Teachers(FIU, rs.getString("nume"));
                if (TATA == null){
                    p.getChildren().add(s);
                }
                if (elem.containsKey(TATA)) {
                    Teachers profesori = (Teachers)elem.get(TATA);                 
                    profesori.getChildren().add(s);
                }
                elem.put(FIU, s);
            }
            model = new ChildPropertyTreeModel(p, "children");
        } catch (ClassNotFoundException ex) {

        } catch (SQLException ex) {

        }

        finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (SQLException ex) {

            }
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException ex) {

            }

        }
    }

    public void setModel(TreeModel model) {
        this.model = model;
    }

    public TreeModel getModel() {
        return model;
    }

    /**
     * Expand all tree nodes
     * @param act
     */
    public void expandAllTreeNodes(ActionEvent act) {
        RowKeySet _disclosedRowKeys = new RowKeySetTreeImpl(true);
        _disclosedRowKeys.setCollectionModel(ModelUtils.toTreeModel(richTree.getValue()));
        richTree.setDisclosedRowKeys(_disclosedRowKeys);

    }


    /**
     *Collapse all richTree nodes
     * @param act
     */
    public void collapseAllTreeNodes(ActionEvent act) {
        RowKeySet _disclosedRowKeys = richTree.getDisclosedRowKeys();
        if (_disclosedRowKeys != null && _disclosedRowKeys.size() > 0) {
            _disclosedRowKeys.clear();
        }
        richTree.setDisclosedRowKeys(_disclosedRowKeys);
    }


    /**
     * ValueChangeEvent for the drop down, this method expands those nodes
     * matching selected value
     * @param valueChangeEvent
     */
    public void valueChangeEventSelectProf(ValueChangeEvent valueChangeEvent) {

        if (richTree != null && richTree.getValue() != null) {
            RowKeySet _disclosedRowKeys = richTree.getDisclosedRowKeys();
            RowKeySet _selectedRowKeys = richTree.getSelectedRowKeys();

            if (_disclosedRowKeys == null) {
                System.out.println("richTree.getDisclosedRowKeys return null!!!");                
                return;
            }
            if (_disclosedRowKeys.size() > 0) {
                _disclosedRowKeys.clear();
                _selectedRowKeys.clear();
            }
            /**
                 * Get the selected value from the drop down
                 * Pass the value to the discloseNodes for keeping the node exanded
                 */
            BigDecimal id_prof = (BigDecimal)valueChangeEvent.getNewValue();
            String name = null;
            for (SelectItem p : getListaProfi())
                if (id_prof == p.getValue()) {
                    name = p.getLabel();
                    break;
                }
            System.out.println("##" + name);
            discloseNodes(name,"CONTAIN");


        }
    }
    
    /**
     * search tree this method expands those nodes
     * matching selected value
     * @param valueChangeEvent
     */
    public String onSearchProf() {
        if (richTree != null && richTree.getValue() != null) {
            RowKeySet _disclosedRowKeys = richTree.getDisclosedRowKeys();
            RowKeySet _selectedRowKeys = richTree.getSelectedRowKeys();

            if (_disclosedRowKeys == null) {
                System.out.println("richTree.getDisclosedRowKeys return null!!!");                
                return "";
            }
            if (_disclosedRowKeys.size() > 0) {
                _disclosedRowKeys.clear();
                _selectedRowKeys.clear();
            }
                discloseNodes(searchString,searchType);
        }
        return "";
    }


    /**
     * This  method to expands nodes matching the 'nodeValueToBeExpanded' parameter
     * @param richTree
     * @param _disclosedRowKeys
     * @param nodeValueToBeExpanded
     * @return
     */
    private boolean discloseNodes(String nodeValueToBeExpanded, String comparator) {

        boolean isFound = false;

        for (int i = 0; i < richTree.getRowCount(); i++) {
            richTree.setRowIndex(i);
            System.out.println("disclosed=" + richTree.getDisclosedRowKeys());
            if (comparator.equals("CONTAIN")) {
                if (richTree.getRowData().toString().contains(nodeValueToBeExpanded)) {
                    richTree.getSelectedRowKeys().clear();
                    richTree.getSelectedRowKeys().add();
                }
            } else {
                if (comparator.equals("START")) {
                    if (richTree.getRowData().toString().startsWith(nodeValueToBeExpanded)) {
                        richTree.getSelectedRowKeys().clear();
                        richTree.getSelectedRowKeys().add();
                    }
                } else {
                    if (comparator.equals("END")) {
                        if (richTree.getRowData().toString().endsWith(nodeValueToBeExpanded)) {
                            richTree.getSelectedRowKeys().clear();
                            richTree.getSelectedRowKeys().add();
                        }
                    }
                }
            }
                    if (richTree.isContainer()) {
                        richTree.enterContainer();
                        if (richTree.getRowCount() > 0 && discloseNodes(nodeValueToBeExpanded, comparator)) {

                            richTree.exitContainer();
                            richTree.getDisclosedRowKeys().add();

                            isFound = true;
                        } else {
                            richTree.exitContainer();
                        }
                    } else {
                        if (richTree.getRowData() != null) {
                            if (comparator.equals("CONTAIN") &&
                                richTree.getRowData().toString().contains(nodeValueToBeExpanded)) {
                                isFound = true;
                            } else {
                                if (comparator.equals("START") &&
                                    richTree.getRowData().toString().startsWith(nodeValueToBeExpanded)) {
                                    isFound = true;
                                } else {
                                    if (comparator.equals("END") &&
                                        richTree.getRowData().toString().endsWith(nodeValueToBeExpanded)) {
                                        isFound = true;
                                    }
                                }
                            }
                        }
                    }
                }
                return isFound;
            }

    public RowKeySet getDisclosedRowKeys() {
        return disclosedRowKeys;
    }


    public void setRichTree(RichTree richTree) {
        this.richTree = richTree;
    }

    public RichTree getRichTree() {
        return richTree;
    }
    private void log(String message) {
        logger.log(ADFLogger.WARNING, message);
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchType(String searchType) {
        this.searchType = searchType;
    }

    public String getSearchType() {
        return searchType;
    }

    public void setSearchAttributes(List searchAttributes) {
        this.searchAttributes = searchAttributes;
    }

    public List getSearchAttributes() {
           
    return searchAttributes;
    }
    }


